/* -+- file  ./kf2/Exposition/Html.cs -+- */
/*
 * kf2 jabber client
 * ~~~~~~~~~~~~~~~~~
 *
 * Copyright (C) 2006-2007 Przemysław Sitek
 * 				<przemyslaw.sitek at wp.pl> 
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */


using System;
using System.Collections.Generic;
using Habazie.kf2.Core;

namespace Habazie.kf2.Exposition
{
	
	public class Html : Gecko.WebControl
	{
		public const string EVENT_PROTOCOL = "kf2";
		private string m_PageTitle = "";
		private string m_Stylesheet = "default.css";
		private System.Text.StringBuilder m_Buffer;

		private Dictionary<string,HtmlEventHandler> m_Handlers;
		
		///<brief>
		///	Default constructor
		///</brief>
		public Html() : base ()
		{
			m_Buffer = new System.Text.StringBuilder ("");
			m_Handlers = new Dictionary<string,HtmlEventHandler> ();
			OpenUri += OnOpenUri;
			Realized += OnXRealized;
		}
		
		public string PageTitle {
			get { return m_PageTitle; }
			set { m_PageTitle = value; }
		}
		
		public string StyleSheet {
			get { return m_Stylesheet; }
			set { m_Stylesheet = value; }
		}
		
		public virtual void Clear ()
		{
//			string url = Util.FindFile ("gecko");
//			OpenStream ("file://" + System.Environment.CurrentDirectory+"/", "text/html");
//			OpenStream ("file://" + url + "/", "text/html");
			AppendData ("<?xml version=\"1.0\" encoding=\"utf-8\"?><html><head><link rel=\"stylesheet\" href=\""+m_Stylesheet+"\"></head><body>");
			if (PageTitle != null)
				AppendData ("<h1>"+PageTitle+"</h1>");
		}		
		
		
		///<brief>
		/// Open a url
		///</brief>
		private void LinkHandler (string uri)
		{
			System.Console.WriteLine ("LinkHandler (\"{0}\");", uri);

			int colon = uri.IndexOf (':');
			if (colon > -1) {
				string protocol = uri.Substring (0, colon);
				string args = uri.Substring (colon + 1);
				
				if (protocol == EVENT_PROTOCOL)
					FireHandler (args);
				
//				if (protocol == "event") {
//					int id = System.Int32.Parse (args);
//					m_EventBox.Process (id);
//				}
			}
		}
		
		
		///<summary>
		///	Add handler for a uri
		///</summary>
		public void AddHandler (string path, HtmlEventHandler handler)
		{
			m_Handlers.Add (path, handler);
		}
		
		
		///<summary>
		///	Remove handler for a uri
		///</summary>
		public void RemoveHandler (string path)
		{
			m_Handlers.Remove (path);
		}
		
		
		public void AppendData (string text)
		{
			if (! IsRealized) {
				Util.Debug ("exposition", "Widget is not realized!");
				m_Buffer.Append (text);
			} else {
				base.AppendData (text);
			}
		}
		
		
		protected void OnXRealized (object o, EventArgs args)
		{
			Util.Debug ("exposition", "OnRealized! ({0})", IsRealized);
			string data = m_Buffer.ToString ();
			Util.Debug ("exposition", "Appending data: {0}", data);
			
			string url = Util.FindFile ("gecko");
			OpenStream ("file://" + url + "/", "text/html");
			base.AppendData (data);
			m_Buffer = new System.Text.StringBuilder ("");
			
		//	base.OnRealized ();
		}
		
		///<summary>
		///	Fire handler
		///</summary>
		protected virtual void FireHandler (string args)
		{
			System.Console.WriteLine ("FireHandler (\"{0}\");", args);
			int question = args.IndexOf ('?');
			string query;
			string uri;
			if (question > -1) {
				query = args.Substring (question + 1);
				uri = args.Substring (0, question);
			} else {
				query = "";
				uri = args;
			}
			
			try {
				HtmlEventHandler h = m_Handlers[uri];
				HtmlEventArgs hargs = new HtmlEventArgs (uri, query);
				if (h != null)
					h (this, hargs);
			} catch (KeyNotFoundException) {
				// handler was not registered
			}
		}
		
		
		///<summary>
		///	Handler for OpenUri event
		///</summary>
		protected virtual void OnOpenUri (object o, Gecko.OpenUriArgs args)
		{
			System.Console.WriteLine ("OnOpenUri (\"{0}\");", LinkMessage);
			LinkHandler (LinkMessage);
			args.RetVal = true;
		}
	}
	
	public delegate void HtmlEventHandler (object sender, HtmlEventArgs args);
	
	public class HtmlEventArgs : System.EventArgs
	{
		private string m_Path;
		private Dictionary<string,string> m_Args;
		
		public HtmlEventArgs (string path, string query) : base ()
		{
			System.Console.WriteLine ("HtmlEventArgs (\"{0}\", \"{1}\")", path, query);
			m_Path = path;
			m_Args = new Dictionary<string,string> ();
			
			string [] a = query.Split ('&');
			foreach (string s in a) {
				int eq = s.IndexOf ('=');
				string key;
				string val;
				if (eq > -1) {
					key = s.Substring (0, eq);
					val = s.Substring (eq + 1);
				} else {
					key = s;
					val = "";
				}
				m_Args.Add (key, val);
				Console.Out.WriteLine (" * '{0}'='{1}'", key, val);
			}
		}		
		
		public string Path {
			get { return m_Path; }
		}
		
		public string this[string name] {
			get { return m_Args[name]; }
		}
	}
}
